﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Yunlib.Common;
using Yunlib.Entity;
using YunLib.API.Models;
using YunLib.BLL;
using YunLib.Common;

namespace YunLib.API.Controllers
{
    public class BorrowBooksController : ApiController
    {
        private ReturnOrBrBLL rob = new ReturnOrBrBLL();
        private ReaderInfoBLL rib = new ReaderInfoBLL();
        private string loginKey = ConfigManager.LoginKey;
        private int Operator = ConfigManager.Operator;

        // GET: api/BorrowBooks
        //[HttpGet]
        //public IEnumerable<string> Get()
        //{
        //    return new string[] { "value1", "value2" };
        //}


        // GET: api/BorrowBooks/5
        [HttpGet]
        public JObject Get(string code,string dz_code,string book_code,string timesstamp,string sign)
        {
            BackMessageModel<BookInfoModel> bm = new BackMessageModel<BookInfoModel>();
            bm.CODE = "400";
            var signstr = "{0}{1}{2}{3}{4}".FormatWith(code, book_code, dz_code, timesstamp, loginKey);
            var sign1 = EncrypAndDecryp.Base64Encode(EncrypAndDecryp.SHA1(signstr).ToLower());
            if (sign1 != sign)
            {
                bm.MESSAGE = "密匙错误";
                return bm.ToJson().ToJObject();
            }
            else
            {
                if (code == "0")
                {
                    DataTable dtUser = rib.GetUser(dz_code);
                    if (Convert.ToDateTime(dtUser.Rows[0]["失效日期"].ToString()) < DateTime.Now && !string.IsNullOrWhiteSpace(dtUser.Rows[0]["挂失注销"].ToString()))
                    {
                        //读者卡失效了
                        bm.MESSAGE = "读者卡已在：{0} 失效".FormatWith(dtUser.Rows[0]["失效日期"].ToString());
                        return bm.ToJson().ToJObject();
                    }
                    else
                    {
                        //读者卡没有失效,就判断密码是否输入正确
                        if (dtUser.Rows.Count > 0 && dtUser != null)
                        {
                            bool HasExpire = false;
                            DataTable dt1 = rob.GetCirculationByUserId(dz_code);
                            var list = DataTable2List<ChangeKuInfo>.ConvertToModel(dt1);
                            foreach (var item in list)
                            {
                                var reTime = item.ShouldReturnTime;
                                if (reTime < DateTime.Now)
                                {
                                    HasExpire = true;
                                }
                            }
                            if (HasExpire)
                            {
                                bm.MESSAGE = "你有过期书籍";
                                return bm.ToJson().ToJObject();
                            }
                            else
                            {
                                if ((int)dtUser.Rows[0]["可外借"] - (int)dtUser.Rows[0]["已外借"] <= 0)
                                {
                                    bm.MESSAGE = "可外借数量已达上限";
                                    return bm.ToJson().ToJObject();
                                }
                                else
                                {

                                    var bookID = rob.GetBookIDByBarCode(book_code);

                                    ChangeLogInfo logInfo = new ChangeLogInfo
                                    {
                                        OperateType = "J",
                                        BarCode = book_code,
                                        LoginAccount = book_code,
                                        DealTime = DateTime.Now,
                                        ID = bookID,
                                        Penalty = 0,
                                        ReaderCode = dtUser.Rows[0][2].ToString(),
                                        Operator = 99
                                    };

                                    //插入流通日志
                                    rob.InsertLTKOneInfo(logInfo);

                                    ChangeKuInfo kuInfo = new ChangeKuInfo
                                    {

                                        ID = bookID,
                                        BarCode = book_code,
                                        LoginAccount = book_code,
                                        BorrowTime = DateTime.Now,
                                        ReaderCode = dtUser.Rows[0][1].ToString(),
                                        OnceBorrowCount = rob.GetOnceBorrowCount(dtUser.Rows[0][2].ToString()),
                                        ShouldReturnTime = DateTime.Now.AddMonths(1)
                                    };
                                    //插入流通库
                                    rob.AddCirculation(kuInfo);

                                    rib.UpdateUserBoorowNum((int)dtUser.Rows[0][1] + 1, dz_code);
                                    bm.MESSAGE = "成功";
                                    bm.CODE = "0000";
                                    return bm.ToJson().ToJObject();
                                }
                            }
                        }
                    }

                }
                else if (code == "1")
                {
                    var bookID = rob.GetBookIDByBarCode(book_code);
                    //配置Entity
                    ChangeLogInfo model1 = new ChangeLogInfo
                    {
                        OperateType = "X",
                        BarCode = book_code,
                        LoginAccount = book_code,
                       // ReaderCode = ck.ReaderCode,
                        DealTime = DateTime.Now,
                        Penalty = 0.00m,
                        Operator = 99,
                        ID = bookID
                    };


                    //在流通库中新增一条记录
                    bool res = rob.InsertLTKOneInfo(model1);
                    if (res)
                    {
                        bm.MESSAGE = "成功";
                        bm.CODE = "0000";
                        return bm.ToJson().ToJObject();
                    }
                    else
                    {
                        bm.MESSAGE = "失败";
                        return bm.ToJson().ToJObject();
                    }
                }
                else
                {
                    bm.MESSAGE = "操作类型错误";
                    return bm.ToJson().ToJObject();
                }
                return bm.ToJson().ToJObject();
            }
        }

        [HttpPost]
        public JObject Post(string code, string dz_code, string book_code, string timesstamp, string sign)
        {
            BackMessageModel<BookInfoModel> bm = new BackMessageModel<BookInfoModel>();
            bm.CODE = "400";
            var signstr = "{0}{1}{2}{3}{4}".FormatWith(code, book_code, dz_code, timesstamp, loginKey);
            var sign1 = EncrypAndDecryp.Base64Encode(EncrypAndDecryp.SHA1(signstr).ToLower());
            if (sign1 != sign)
            {
                bm.MESSAGE = "密匙错误";
                return bm.ToJson().ToJObject();
            }
            else
            {
                if (code == "0")
                {
                    DataTable dtUser = rib.GetUser(dz_code);
                    if (Convert.ToDateTime(dtUser.Rows[0]["失效日期"].ToString()) < DateTime.Now)
                    {
                        //读者卡失效了
                        bm.MESSAGE = "读者卡已在：{0} 失效".FormatWith(dtUser.Rows[0]["失效日期"].ToString());
                        return bm.ToJson().ToJObject();
                    }
                    else
                    {
                        //读者卡没有失效,就判断密码是否输入正确
                        if (dtUser.Rows.Count > 0 && dtUser != null)
                        {
                            bool HasExpire = false;
                            DataTable dt1 = rob.GetCirculationByUserId(dz_code);
                            var list = DataTable2List<ChangeKuInfo>.ConvertToModel(dt1);
                            foreach (var item in list)
                            {
                                var reTime = item.ShouldReturnTime;
                                if (reTime < DateTime.Now)
                                {
                                    HasExpire = true;
                                }
                            }
                            if (HasExpire)
                            {
                                bm.MESSAGE = "你有过期书籍";
                                return bm.ToJson().ToJObject();
                            }
                            else
                            {
                                if ((int)dtUser.Rows[0]["可外借"] - (int)dtUser.Rows[0]["已外借"] <= 0)
                                {
                                    bm.MESSAGE = "可外借数量已达上限";
                                    return bm.ToJson().ToJObject();
                                }
                                else
                                {

                                    var bookID = rob.GetBookIDByBarCode(book_code);

                                    ChangeLogInfo logInfo = new ChangeLogInfo
                                    {
                                        OperateType = "J",
                                        BarCode = book_code,
                                        LoginAccount = book_code,
                                        DealTime = DateTime.Now,
                                        ID = bookID,
                                        Penalty = 0,
                                        ReaderCode = dtUser.Rows[0][2].ToString(),
                                        Operator = 99
                                    };

                                    //插入流通日志
                                    rob.InsertLTKOneInfo(logInfo);

                                    ChangeKuInfo kuInfo = new ChangeKuInfo
                                    {

                                        ID = bookID,
                                        BarCode = book_code,
                                        LoginAccount = book_code,
                                        BorrowTime = DateTime.Now,
                                        ReaderCode = dtUser.Rows[0][1].ToString(),
                                        OnceBorrowCount = rob.GetOnceBorrowCount(dtUser.Rows[0][1].ToString()),
                                        ShouldReturnTime = DateTime.Now.AddMonths(1)
                                    };
                                    //插入流通库
                                    rob.AddCirculation(kuInfo);

                                    rib.UpdateUserBoorowNum((int)dtUser.Rows[0]["已外借"] + 1, dz_code);
                                    bm.MESSAGE = "成功";
                                    bm.CODE = "0000";
                                    return bm.ToJson().ToJObject();
                                }
                            }
                        }
                    }

                }
                else if (code == "1")
                {
                    var bookID = rob.GetBookIDByBarCode(book_code);
                    //配置Entity
                    ChangeLogInfo model1 = new ChangeLogInfo
                    {
                        OperateType = "X",
                        BarCode = book_code,
                        LoginAccount = book_code,
                     //   ReaderCode = book.ReaderCode,
                        DealTime = DateTime.Now,
                        Penalty = 0.00m,
                        Operator = 99,
                        ID = bookID
                    };


                    //在流通库中新增一条记录
                    bool res = rob.InsertLTKOneInfo(model1);
                    
                    if (res)
                    {
                        bm.MESSAGE = "成功";
                        bm.CODE = "0000";
                        return bm.ToJson().ToJObject();
                    }
                    else
                    {
                        bm.MESSAGE = "失败";
                        return bm.ToJson().ToJObject();
                    }
                }
                else
                {
                    bm.MESSAGE = "操作类型错误";
                    return bm.ToJson().ToJObject();
                }
                return bm.ToJson().ToJObject();
            }
        }

        // POST: api/BorrowBooks
        [HttpPost]
        public JObject Post(SearchModel model)
        {
            BackMessageModel<BookInfoModel> bm = new BackMessageModel<BookInfoModel>();
            bm.CODE = "400";
            try
            {
               
                var signstr = "{0}{1}{2}{3}{4}".FormatWith(model.code, model.book_code, model.dz_code, model.timesstamp, loginKey);
                var sign = EncrypAndDecryp.Base64Encode(EncrypAndDecryp.SHA1(signstr).ToLower());
                if (sign != model.sign)
                {
                    bm.MESSAGE = "密匙错误";
                    return bm.ToJson().ToJObject();
                }
                else
                {
                    if (model.code == "0")
                    {
                        try
                        {
                            DataTable dt = rob.GetSIP2BookInfoByBarCode(model.book_code);

                            if (dt.Rows.Count == 0)
                            {
                                bm.MESSAGE = "图书条码错误";
                                return bm.ToJson().ToJObject();
                            }

                            bool canBorrow = dt.Rows[0]["允许外借"].ToBool();
                            if (!canBorrow)
                            {
                                bm.MESSAGE = "|bm.MESSAGE图书借阅失败失败原因===>该书不可外借";
                                return bm.ToJson().ToJObject();
                            }
                            
                            DataTable dtUser = rib.GetUser(model.dz_code);
                            if (dtUser.Rows.Count <= 0)
                            {
                                bm.MESSAGE = "读者条码错误";
                                return bm.ToJson().ToJObject();;
                            }

                            if (Convert.ToDateTime(dtUser.Rows[0]["失效日期"].ToString()) < DateTime.Now)
                            {
                                //读者卡失效了

                                bm.MESSAGE = "读者卡已失效";
                                return bm.ToJson().ToJObject();;
                            }
                            string str = dtUser.Rows[0]["挂失日期"].ToString();
                            if (!string.IsNullOrWhiteSpace(dtUser.Rows[0]["挂失日期"].ToString()))
                            {
                                bm.MESSAGE = "读者卡已失效";
                                return bm.ToJson().ToJObject();;
                            }

                            

                            bool HasExpire = false;
                            DataTable dt1 = rob.GetCirculationByUserId(model.dz_code);
                            var list = DataTable2List<ChangeKuInfo>.ConvertToModel(dt1);
                            foreach (var item in list)
                            {
                                var reTime = item.ShouldReturnTime;
                                if (reTime < DateTime.Now)
                                {
                                    HasExpire = true;
                                }
                            }
                            if (HasExpire)
                            {
                                bm.MESSAGE = "有超期书籍未归还";
                                return bm.ToJson().ToJObject();;
                            }
                            else
                            {
                                if ((int)dtUser.Rows[0]["可外借"] - (int)dtUser.Rows[0]["已外借"] <= 0)
                                {
                                    bm.MESSAGE = "可外借数量已达上限";
                                    return bm.ToJson().ToJObject();;
                                }
                                else
                                {
                                    var bb = rob.GetBorrowBooksInfoByBarcode(model.book_code);
                                    if (bb != null)
                                    {
                                        bm.MESSAGE = "该书已借阅";
                                        return bm.ToJson().ToJObject();;
                                    }

                                    bool flag = rib.UpdateUserBoorowNum((int)dtUser.Rows[0]["已外借"] + 1, model.dz_code);

                                    if (!flag)
                                    {
                                        bm.MESSAGE = "修改用户借阅信息失败";
                                        return bm.ToJson().ToJObject();;
                                    }

                                    DataTable dtc = rob.GetcirculationParmar(dt.Rows[0]["虚拟库室"].ToString(), dtUser.Rows[0]["级别代码"].ToString(), dtUser.Rows[0]["单位代码"].ToString());

                                    if (dtc.Rows.Count == 0)
                                    {
                                        bm.MESSAGE = "获取流通参数定义失败";
                                        return bm.ToJson().ToJObject();;
                                    }

                                    DateTime returnTime = DateTime.Now;
                                    if (dtc.Rows[0]["外借期限类型"].ToString() == "M")
                                    {

                                        returnTime = DateTime.Now.AddMonths(int.Parse(dtc.Rows[0]["外借期限"].ToString()));
                                    }
                                    else if (dtc.Rows[0]["外借期限类型"].ToString() == "D")
                                    {
                                        returnTime = DateTime.Now.AddDays(int.Parse(dtc.Rows[0]["外借期限"].ToString()));
                                    }
                                    else
                                    {
                                        returnTime = DateTime.Now.AddYears(int.Parse(dtc.Rows[0]["外借期限"].ToString()));
                                    }

                                    ChangeKuInfo kuInfo = new ChangeKuInfo
                                    {

                                        ID = int.Parse(dt.Rows[0]["主键码"].ToString()),
                                        BarCode = model.book_code,
                                        LoginAccount = model.book_code,
                                        BorrowTime = DateTime.Now,
                                        ReaderCode = model.dz_code,
                                        OnceBorrowCount = rob.GetOnceBorrowCount(dtUser.Rows[0][2].ToString()),
                                        ShouldReturnTime = returnTime
                                    };


                                    //插入流通库
                                    bool flag2 = rob.AddCirculation(kuInfo);
                                    if (!flag2)
                                    {
                                        bm.MESSAGE = "插入流通记录失败";
                                        rib.UpdateUserBoorowNum((int)dtUser.Rows[0]["已外借"] + 1, model.dz_code);
                                        return bm.ToJson().ToJObject();;
                                    }


                                    ChangeLogInfo logInfo = new ChangeLogInfo
                                    {
                                        OperateType = "J",
                                        BarCode = model.book_code,
                                        LoginAccount = model.book_code,
                                        DealTime = DateTime.Now,
                                        ID = int.Parse(dt.Rows[0]["主键码"].ToString()),
                                        Penalty = 0,
                                        ReaderCode = model.dz_code,
                                        Operator = Operator
                                    };

                                    //插入流通日志
                                    flag = rob.InsertLTKOneInfo(logInfo);
                                    if (!flag)
                                    {
                                        bm.MESSAGE = "插入流通日志失败";
                                        rib.UpdateUserBoorowNum((int)dtUser.Rows[0]["已外借"] + 1, model.dz_code);
                                        rob.DeleteChangeInfoByBarCode(logInfo.BarCode);
                                        return bm.ToJson().ToJObject();;
                                    }
                                    else
                                    {

                                        
                                        bm.MESSAGE = "借书处理成功";

                                        return bm.ToJson().ToJObject();;
                                    }

                                }

                            }
                        }
                        catch (Exception ex)
                        {
                            bm.MESSAGE = "图书借阅失败失败";
                            LogManager.WriteLogs(ex.Message, ex.StackTrace, LogFile.Error);
                            return bm.ToJson().ToJObject();;
                        }
                    

                    }
                    else if (model.code == "1")
                    {
                        //判断条码是否为空
                        if (string.IsNullOrWhiteSpace(model.book_code))
                        {
                            bm.MESSAGE += "还书条码不能为空";
                            return bm.ToJson().ToJObject();
                        }
                        //获取图书馆藏信息
                        DataTable dt = rob.GetSIP2BookInfoByBarCode(model.book_code);

                        if (dt.Rows.Count == 0)
                        {
                            bm.MESSAGE = "图书条码错误";
                            return bm.ToJson().ToJObject();
                        }

                        ChangeKuInfo ck = rob.GetBorrowBooksInfoByBarcode(model.book_code);
                        if (ck == null)
                        {

                            bm.MESSAGE =  "没有借阅记录";
                            return bm.ToJson().ToJObject();
                        }

                        var dtUser = rib.GetUser(ck.ReaderCode);


                        DataTable dtc = rob.GetcirculationParmar(ck.DummyKu.ToString(), dtUser.Rows[0]["级别代码"].ToString(), dtUser.Rows[0]["单位代码"].ToString());

                        string str11 = dtc.Rows[0]["允许续借次数"].ToString();
                        if (ck.OnceBorrowCount >= int.Parse(dtc.Rows[0]["允许续借次数"].ToString()))
                        {
                            bm.MESSAGE = "读者续借次数达到上限，请归还再借！";
                            return bm.ToJson().ToJObject();
                        }

                        DateTime returnTime = ck.ShouldReturnTime;

                        if (dtc.Rows[0]["续借期限类型"].ToString() == "M")
                        {

                            returnTime = returnTime.AddMonths(int.Parse(dtc.Rows[0]["续借期限"].ToString()));
                        }
                        else if (dtc.Rows[0]["续借期限类型"].ToString() == "D")
                        {
                            returnTime = returnTime.AddDays(int.Parse(dtc.Rows[0]["续借期限"].ToString()));
                        }
                        else
                        {
                            returnTime = returnTime.AddYears(int.Parse(dtc.Rows[0]["续借期限"].ToString()));
                        }

                        bool flag = rob.UpdateChangeKUReBackTime(model.book_code, returnTime, ck.OnceBorrowCount + 1);
                        if (!flag)
                        {
                            bm.MESSAGE = "续借处理失败 原因:=>修改归还时间出错！";
                            return bm.ToJson().ToJObject();

                        }
                        var book = rob.GetBooksInfoByBarcode(model.book_code);
                        //配置Entity
                        ChangeLogInfo model1 = new ChangeLogInfo
                        {
                            OperateType = "X",
                            BarCode = model.book_code,
                            LoginAccount = model.book_code,
                            ReaderCode = book.ReaderCode,
                            DealTime = DateTime.Now,
                            Penalty = 0.00m,
                            Operator = Operator,
                            ID = book.ID
                        };


                        //在流通库中新增一条记录
                        bool res = rob.InsertLTKOneInfo(model1);
                        if (res)
                        {
                            bm.MESSAGE =  "续借处理成功!";
                           
                            return bm.ToJson().ToJObject();
                        }
                        else
                        {
                            bm.MESSAGE = "】续借处理失败,原因:=>插入流通日志失败！";
                            return bm.ToJson().ToJObject();
                        }
                    }
                    else
                    {
                        bm.MESSAGE = "操作类型错误";
                        return bm.ToJson().ToJObject();
                    }
                    return bm.ToJson().ToJObject();
                }
            }catch (Exception ex)
            {
                LogManager.ErrorRecord("【{0}】:{1}".FormatWith(DateTime.Now, ex.Message));
                bm.MESSAGE = ex.Message;
                return bm.ToJson().ToJObject();

            }
        }

        // PUT: api/BorrowBooks/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/BorrowBooks/5
        public void Delete(int id)
        {
        }
    }
}
